package com.zhihao.zhihaopicturebackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.zhihao.zhihaopicturebackend.config.CosClientConfig;
import com.zhihao.zhihaopicturebackend.exception.BusinessException;
import com.zhihao.zhihaopicturebackend.exception.ErrorCode;
import com.zhihao.zhihaopicturebackend.exception.ThrowUtils;
import com.zhihao.zhihaopicturebackend.manager.CosManager;
import com.zhihao.zhihaopicturebackend.model.dto.file.UploadPictureResult;
import com.zhihao.zhihaopicturebackend.model.enums.PictureFormatEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author Jackson
 * @create 2024/12/23 16:39
 * @description 图片上传模板抽象类---模板方法模型(设计模式)
 */
@Slf4j
public abstract class PictureUploadTemplate {

    /*
        图片文件上传(方式1：文件   方式2：url链接)
            1. 文件校验
            2. 获取上传地址
            3. 获取本地临时文件
            (公用)    4. 上传到对象存储
                     5. 封装图片解析信息
                     6. 清理临时文件
     */

    /**
     * 校验输入源（本地文件或 URL）
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 获取输入源的原始文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;


    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    // 定义一个自定义的日期格式化器，格式为"yyyyMMdd"
    public static final DateTimeFormatter CUSTOM_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * 模板方法，定义上传流程
     *
     * @param inputSource      文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 1. 校验图片
        validPicture(inputSource);
        // 2. 图片上传地址
        // 图片上传地址(相当于文件名脱敏操作)   时间+uuid(10位).文件后缀(eg: 20241223_1234567890.png)
        String uuid = RandomUtil.randomString(10);
        String originFilename = getOriginFilename(inputSource);
        String uploadFilename = String.format("%s_%s.%s", DateUtil.format(new Date(), CUSTOM_DATE_FORMATTER),
                uuid, FileUtil.getSuffix(originFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        //
        File file = null;
        try {
            // 3. 创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 处理文件来源（本地或 URL ---> file）
            processFile(inputSource, file);

            // 4. 上传图片到对象存储(同时返回文件信息)
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo(); // 原始文件上传结果
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();    // 处理规则文件结果
            List<CIObject> objectList = processResults.getObjectList(); // rules规则的个数等于len(list)
            // 相当于以后页面展示的都是webp格式的图片(不会改变长宽及比例，只会改变格式和大小size)
            if (CollUtil.isNotEmpty(objectList)) {
                CIObject compressedCiObject = objectList.get(0);
                CIObject thumbnailCiObject = compressedCiObject;
                // 有生成缩略图，才得到缩略图,否则就是用webp格式的压缩图
                if (objectList.size() > 1) {
                    thumbnailCiObject = objectList.get(1);
                }
                // 压缩/缩略操作成功，则构造新的返回结果
                return buildResult(originFilename, uploadPath,imageInfo, compressedCiObject,thumbnailCiObject);
            }
            // 压缩/缩略操作失败，默认只构造原图返回结果
            return buildResult(originFilename, file, uploadPath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            // 6. 清理临时文件
            deleteTempFile(file);
        }
    }

    /**
     * webp格式压缩图 压缩成功则按照压缩图信息入库
     */
    private UploadPictureResult buildResult(String originFilename, String uploadPath, ImageInfo imageInfo, CIObject compressedCiObject, CIObject thumbnailCiObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        // 主色调
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // url
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);   // 原图
        uploadPictureResult.setWebpUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());  // webp压缩图(后续使用这个)
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());  // 缩略图
        return uploadPictureResult;
    }


    /**
     * 封装返回结果  非webp格式压缩图()
     */
    private UploadPictureResult buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicSize(FileUtil.size(file));
        // 主色调
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // url
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        //TODO:缩略图
        return uploadPictureResult;
    }


    /**
     * 清理临时文件
     *
     * @param file
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
}